<?php

namespace app\common\service;

use app\common\service\Base;
use app\common\service\Material as MaterialService;

class MaterialStockCutting extends Base
{

	/**
	 * 根据ID获取行记录
	 *
	 * @author KING
	 * @date 2020年7月9日
	 *
	 * @param integer $id
	 * @param string $field
	 * @return array
	 */
	public function getInfoById($id, $field='*') {
		if (empty($id)) return [];
		return db('material_stock_cutting')->where('id', $id)->field($field)->findOrEmpty();
	}

	/**
	 * 根据订单ID和物料ID获取行记录
	 *
	 * @author KING
	 * @date 2020年7月9日
	 *
	 * @param integer $orderId
	 * @param integer $materialId
	 * @param string $field
	 * @return array
	 */
	public function getInfoByMaterialId($orderId, $materialId, $field='*') {
		if (empty($orderId) || empty($materialId)) return [];
		return db('material_stock_cutting')->where('order_id', $orderId)->where('material_id', $materialId)->field($field)->findOrEmpty();
	}

	/**
	 * 同步实际使用料
	 *
	 * @author King
	 * @date 2020年8月27日
	 *
	 * @param integer $orderId
	 * @param integer $materialId
	 */
	public function sync($orderId, $materialId) {
		$whereUse = [
			['order_id', '=', $orderId],
			['material_id', '=', $materialId],
			['status', '=', 2],
		];
		$length = db('material_stock_use')->where($whereUse)->sum('true_metre');

		$where = [
			['order_id', '=', $orderId],
			['material_id', '=', $materialId],
		];
		$info = db('material_stock_cutting')->where($where)->field('id,client_ordernum')->findOrEmpty();
		if ($info) {
			$upData = [
				'length' => $length,
				'update_time' => time(),
			];
			db('material_stock_cutting')->where($where)->update($upData);
		} elseif($length > 0) {
			$materialService = new MaterialService();
			$materialName = $materialService->getMaterialName($materialId);
			if($materialService->checkIsIncludeKeys($materialName)) return true;

			$clientOrdernum = db('material_stock_use')->where($whereUse)->limit(1)->value('client_ordernum', '');
			$upData = [
				'order_id' => $orderId,
				'material_id' => $materialId,
				'client_ordernum' => $clientOrdernum,
				'length' => $length,
				'create_time' => time(),
				'update_time' => time(),
			];
			db('material_stock_cutting')->insertGetId($upData);
		}
		return true;
	}
}